#!/usr/bin/env node
/**
 * 项目初始化工具
 * @author wenke
 */
const program = require("commander");
const fs = require("fs");
const chalk = require("chalk");
const exec = require("child_process").exec;
const figlet = require("figlet");
const clui = require("clui");
const inquirer = require("inquirer");
const templates = require("./templates");
const rimraf = require("rimraf");

const Spinner = clui.Spinner;
const status = new Spinner("正在下载...");

const cooperate = chalk.yellow(
  figlet.textSync("- cooperate cli -", {
    horizontalLayout: "full",
  })
);
console.log(cooperate);

program
  .version(require("./package").version, "-v, --version")
  .usage("coop init")
  .description("<Cooperate> Generate a new project")
  .on("--help", () => {
    console.log();
  });

program
  .command("init")
  .alias("i")
  .action(async () => {
    const choices = [];
    Object.keys(templates).forEach((key) => {
      const tpl = templates[key];

      choices.push({
        name: `<${key}> ${tpl.description}`,
        value: key,
      });
    });

    const answers = await inquirer.prompt([
      {
        name: "projectName",
        type: "input",
        message: "请输入你的项目名称：",
        validate: function (value) {
          if (value.length) {
            return true;
          } else {
            return "请输入你的项目名称";
          }
        },
      },
      {
        name: "templateName",
        type: "list",
        message: "请选择你需要的项目模板：",
        choices,
      },
    ]);

    const tpl = templates[answers.templateName];

    const { url, branch } = tpl;

    let branchName = branch;

    if (branch instanceof Array) {
      const branchAnswer = await inquirer.prompt([
        {
          name: "branchName",
          type: "list",
          message: "请选择项目分支类型",
          choices: branch.map((key) => ({ name: key, value: key })),
        },
      ]);

      branchName = branchAnswer.branchName;
    }

    const cmdString = [`git clone -b ${branchName} ${url} ${answers.projectName}`, `cd ${answers.projectName}`].join(" && ");

    status.start();

    exec(cmdString, (error) => {
      status.stop();

      if (error) {
        console.log("错误：", chalk.red(JSON.stringify(error)));
        process.exit();
      }

      // TODO: 在模板中增加条件编译项目

      // 删除模板下载到的 .git 目录
      rimraf(`./${answers.projectName}/.git`, (err) => {
        if (err) console.log(err);
        console.log(chalk.green("\n √ 下载完成!"));
        console.log(chalk.cyan(`\n cd ${answers.projectName} && npm install && npm run serve \n`));
        process.exit();
      });
    });
  });

program.parse(process.argv);
